import cv2
import flet as ft
import json
import os.path

import numpy as np
from flet_core import FilePicker

from utils import snack_bar, mkdir
from PIL import Image

from views.treasure_dialogs.baseDialog import BaseDialog2

"""
去除水印
去掉右下角的水印步骤
1、从源图片，截取右下角部分，另存为新图片；
2、识别水印，颜色值为：[200, 200, 200]~[255, 255, 255]
3、去掉水印，还原图片；
4、把源图片、去掉水印的新图片，进行重叠合并；
"""


class ClearWatermar(BaseDialog2):
    def __init__(self, page: ft.Page):
        self.page = page
        self.choose_file_dialog = None
        # 创建关闭按钮
        self.close_btn = ft.IconButton(
            icon=ft.icons.CLOSE_OUTLINED,
            on_click=self.close_dlg
        )

        # 创建选择文件按钮
        self.choose_file_btn = ft.FloatingActionButton(
            "选择文件",
            on_click=self.show_file_picker,
            width=300
        )

        row = ft.Row(
            alignment=ft.MainAxisAlignment.CENTER  # 水平居中
        )
        column = ft.Column([self.choose_file_btn])
        # 使用 Column 控件将 Row 和 Column 垂直堆叠
        self.content = ft.Column(controls=[row, column])

        # 创建底层对话框的内容
        self.base_content = ft.Column(controls=[row, column],
                                      alignment=ft.MainAxisAlignment.CENTER,  # 垂直居中
                                      horizontal_alignment=ft.CrossAxisAlignment.CENTER  # 水平居中
                                      )

        # 创建底层对话框
        self.base_dialog = ft.Container(
            content=ft.Card(
                content=ft.Column([
                    ft.Row([
                        ft.Text("水印去除"),
                        self.close_btn  # 关闭按钮放在右上角
                    ], alignment=ft.MainAxisAlignment.SPACE_BETWEEN),
                    self.base_content
                ]),
                elevation=10,
                margin=ft.margin.all(20),
            ),
            visible=True,  # 底层对话框默认可见
            height=self.page.window_height * 0.8,  # 设置高度为页面高度的 80%
            width=self.page.window_width,  # 可选：设置宽度为页面宽度
            alignment=ft.alignment.center  # 将内容居中对齐
        )

        # 使用Stack来堆叠两个对话框
        self.stack = ft.Stack(controls=[self.base_dialog])

        # 文件选择器
        self.file_picker = FilePicker(on_result=self.on_file_picker_result)
        self.page.overlay.append(self.file_picker)
        self.page.update()

    def show_file_picker(self, e):
        # 显示文件选择器
        self.file_picker.pick_files(allowed_extensions=['jpg', 'jpeg', 'png'])

    def on_file_picker_result(self, e: ft.FilePickerResultEvent):
        if e.files:
            for file in e.files:
                # 显示图片预览
                data = json.loads(e.data)
                self.file_path = data["files"][0]["path"]
                print(self.file_path)
                # 这里可以上传文件
                # file_picker.upload(file, upload_url, method="PUT")
                # 创建一个 Image 控件，用于显示原始图片
                # 使用 GestureDetector 来包裹 Image 控件，以便监听点击事件
                self.imageBefor = ft.GestureDetector(
                    on_double_tap=self.show_prompt,
                    content=ft.Image(src=self.file_path, width=200, height=200)
                )
                # 创建一个 Image 控件，用于预留显示处理后的图片
                self.imageAfter = ft.Image(src="aaa.jpg", width=200, height=200,
                                           error_content=ft.Text("处理后显示", color=ft.colors.RED))
                # 将图片控件添加到列布局中
                row1 = ft.Row(controls=[self.imageBefor, self.imageAfter],
                              alignment=ft.MainAxisAlignment.CENTER  # 水平居中
                              )

                self.setting_img_btn = ft.ElevatedButton("处理", on_click=self.clear_watermar, width=300)
                # 将新控件添加到底层对话框的内容中
                self.base_content.controls.append(row1)
                self.base_content.controls.append(self.setting_img_btn)
                # 更新页面以显示新控件
                self.page.update()

    # 修改图片大小
    async def clear_watermar(self, file_path):
        path = self.file_path

        pure_path = os.path.dirname(path)
        print(pure_path)
        file_name = os.path.basename(path)
        print(file_name)
        new_file_dir = pure_path + '/new_img/'
        mkdir(new_file_dir)
        newPath = new_file_dir + 'after_' + file_name

        img = cv2.imread(path, 1)
        hight, width, depth = img.shape[0:3]

        # 截取
        cropped = img[int(hight * 0.8):hight, int(width * 0.7):width]  # 裁剪坐标为[y0:y1, x0:x1]
        cv2.imwrite(newPath, cropped)
        imgSY = cv2.imread(newPath, 1)

        # 图片二值化处理，把[200,200,200]-[250,250,250]以外的颜色变成0
        thresh = cv2.inRange(imgSY, np.array([200, 200, 200]), np.array([250, 250, 250]))
        # 创建形状和尺寸的结构元素
        kernel = np.ones((3, 3), np.uint8)
        # 扩展待修复区域
        hi_mask = cv2.dilate(thresh, kernel, iterations=10)
        specular = cv2.inpaint(imgSY, hi_mask, 5, flags=cv2.INPAINT_TELEA)
        cv2.imwrite(newPath, specular)

        # 覆盖图片
        imgSY = Image.open(newPath)
        img = Image.open(path)
        img.paste(imgSY, (int(width * 0.7), int(hight * 0.8), width, hight))
        img.save(newPath)
        self.imageAfter.src = newPath
        snack_bar(self.page, f"转换完成，已保存")
